<template>
  <n-h4>基本信息</n-h4>
  <n-grid cols="s:1 m:2 l:3 xl:4" :x-gap="20" :y-gap="20" responsive="screen">
    <n-form-item-gi label-placement="left" label="用户昵称">
      <n-input v-model:value="userData.nickName" placeholder="请输入用户名称" disabled />
    </n-form-item-gi>

    <n-form-item-gi label-placement="left" label="登录账号">
      <n-input v-model:value="userData.userName" placeholder="请输入手机号码" disabled />
    </n-form-item-gi>
  </n-grid>

  <n-h4>角色信息</n-h4>
  <n-data-table
    ref="tableRef"
    :loading="loading"
    :columns="columns"
    :data="tableData"
    :row-key="(row: any) => row.roleId"
    v-model:checked-row-keys="checkedRows"
    @update:checked-row-keys="handleChcekedRowKeys"
  />

  <n-space class="pt-15" justify="center">
    <n-button type="default" @click="$router.back()">返回</n-button>
    <n-button type="primary" @click="handleSave" :loading="saveLoading" :disabled="saveLoading">
      保存
    </n-button>
  </n-space>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getUser, getAuthRole, updateUserRole } from '@/apis/system/user';
import { useMessage } from 'naive-ui';

const router = useRouter();
const route = useRoute();
const message = useMessage();
const userData = ref<any>({});
const tableData = ref([]);
const loading = ref(false);
const saveLoading = ref(false);
const checkedRows = ref<any>([]);

const columns = [
  {
    type: 'selection',
    width: 50,
    align: 'center',
    checked: (row: any) => {
      return row.flag;
    },
  },
  {
    title: '角色编号',
    key: 'roleId',
  },
  {
    title: '角色名称',
    key: 'roleName',
  },
  {
    title: '权限字符',
    key: 'roleKey',
  },
  {
    title: '创建时间',
    key: 'createTime',
  },
];

async function init() {
  loading.value = true;
  const userId: string = route.params.userId as string;
  try {
    const userRes: any = await getUser(userId);
    userData.value = userRes.data?.user;

    const roleRes: any = await getAuthRole(userId);
    tableData.value = roleRes.data?.roles || [];
    // 筛选出自动勾上的行
    checkedRows.value = tableData.value
      .filter((item: any) => item.flag)
      .map((item: any) => item.roleId);
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

function handleChcekedRowKeys(keys: Array<string | number>, rows: object[]) {
  checkedRows.value = keys;
}

async function handleSave() {
  saveLoading.value = true;
  try {
    const res: any = await updateUserRole({
      userId: userData.value.userId,
      roleIds: checkedRows.value,
    });
    if (res.code === 200) {
      message.success('保存成功');
      router.back();
    }
  } catch (error) {
  } finally {
    saveLoading.value = false;
  }
}

onMounted(() => {
  init();
});
</script>

<style lang="less" scoped></style>
